﻿using System;
using System.Collections.Generic;
using System.Linq;


namespace FireBus.Shell
{
	public static class CommandLineExtensions
	{
		public static IEnumerable<String> SplitCommandLine(this String commandLine)
		{
			bool inQuotes = false;

			return
				commandLine.Split(
					c =>
					{
						if (c == '\"')
							inQuotes = !inQuotes;

						return !inQuotes && c == ' ';
					})
					.Select(
						arg => arg.Trim().TrimMatchingQuotes('\"'))
					.Where(
						arg => !String.IsNullOrEmpty(arg));
		}

		public static IEnumerable<String> Split(
			this String input, Func<Char, Boolean> controller)
		{
			int nextPiece = 0;

			for (int c = 0; c < input.Length; c++)
			{
				if (controller(input[c]))
				{
					yield return input.Substring(nextPiece, c - nextPiece);
					nextPiece = c + 1;
				}
			}

			yield return input.Substring(nextPiece);
		}

		public static string TrimMatchingQuotes(this String input, char quote)
		{
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			if ((input.Length >= 2) &&
				(input[0] == quote) && (input[input.Length - 1] == quote))
				return input.Substring(1, input.Length - 2);

			return input;
		}
	}
}
